package com.red.wood.common.domain;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.red.wood.common.JsonMapper;


/**
 * 控制器支持类
 */
public abstract class BaseController {

	/**
	 * 日志对象
	 */
	private final static Logger log = LoggerFactory.getLogger(BaseController.class);

	/**
	 * 管理基础路径
	 */
	@Value("${adminPath}")
	protected String adminPath;
	
	/**
	 * 前端基础路径
	 */
	@Value("${frontPath}")
	protected String frontPath;
	
	/**
	 * 前端URL后缀
	 */
	@Value("${urlSuffix}")
	protected String urlSuffix;
	
	/**列表中分页，排序，全局检索功能  此方法适用于list中数据分页      参数  **/
	public String tojson(HttpServletRequest request, HttpServletResponse response ,List list,int count) {   
		String sEcho = ""; 			//分页相关
		String iDisplayStart = "";	//开始显示行   
		String iDisplayLength = "";	//每页显示的长度 
		String sSearch="";			//全局收索  
		String iSortCol_0="";		//排序列
		String sSortDir_0="";		//排序
		int s = 0;//开始行
		int e = 0;//显示记录
		String jsondata = request.getParameter("aoData");   
		JSONArray jsonarray = JSONArray.fromObject(jsondata);
		if(jsondata!=null){
			for (int i = 0; i<jsonarray.size(); i++) {       
				JSONObject obj = (JSONObject) jsonarray.get(i); 
			   if (obj.get("name").equals("sEcho"))     
				   sEcho = obj.get("value").toString();     
			   if (obj.get("name").equals("iDisplayStart"))     //开始显示行      
				   iDisplayStart = obj.get("value").toString();     
			   if (obj.get("name").equals("iDisplayLength"))     //每页显示的长度      
				   iDisplayLength = obj.get("value").toString(); 
			   if (obj.get("name").equals("sSearch"))     //全局收索      
				   sSearch = obj.get("value").toString(); 
			   if (obj.get("name").equals("iSortCol_0"))     //排序列     
				   iSortCol_0 = obj.get("value").toString(); 
			   if (obj.get("name").equals("sSortDir_0"))     //排序     
				   sSortDir_0 = obj.get("value").toString(); 
			}
			
			s = Integer.parseInt(iDisplayStart);
			e = Integer.parseInt(iDisplayStart)+Integer.parseInt(iDisplayLength);
		}
		
		//如果收索字段不为空，则进行收索过滤
		if(StringUtils.isNotEmpty(sSearch)){
			list = this.getSearch(list, sSearch);
		}
		
		String json = null; // 返回的json数据  
		String aaData=JSONArray.fromObject(list.subList(s, e>list.size()?list.size():e)).toString();    
		json =  "{\"sEcho\":"+sEcho+",\"iTotalRecords\":"+count+",\"iTotalDisplayRecords\":"+list.size()+",\"aaData\":"+aaData+"}";  
		
		return json;    
	}
	//收索和排序方法，按照参数对数据进行收索和排序
	public List<Map<String, String>> getSearch(List<Map<String, String>> list,String search){
		
		List<Map<String, String>> listA = new ArrayList<Map<String, String>>();
		for (Map<String, String> map : list) {
				Set<String> set = map.keySet();
				for (String str : set) {
					Object value = map.get(str);
					if(StringUtils.isNotEmpty(str)&&value!=null&&value.toString().indexOf(search)!=-1){
						listA.add(map);
						break;
					}
				}
		}
		return listA;
	}
	
	/**
	 * 添加Model消息
	 * @param message
	 */
	protected void addMessage(Model model, String... messages) {
		StringBuilder sb = new StringBuilder();
		for (String message : messages){
			sb.append(message).append(messages.length>1?"<br/>":"");
		}
		model.addAttribute("message", sb.toString());
	}
	
	/**
	 * 添加Flash消息
	 * @param message
	 */
	protected void addMessage(RedirectAttributes redirectAttributes, String... messages) {
		StringBuilder sb = new StringBuilder();
		for (String message : messages){
			sb.append(message).append(messages.length>1?"<br/>":"");
		}
		redirectAttributes.addFlashAttribute("message", sb.toString());
	}
	
	/**
	 * 客户端返回JSON字符串
	 * @param response
	 * @param object
	 * @return
	 */
	protected String renderString(HttpServletResponse response, Object object) {
		return renderString(response, JsonMapper.toJsonString(object), "application/json");
	}
	
	/**
	 * 客户端返回字符串
	 * @param response
	 * @param string
	 * @return
	 */
	protected String renderString(HttpServletResponse response, String string, String type) {
		try {
			response.reset();
	        response.setContentType(type);
	        response.setCharacterEncoding("utf-8");
			response.getWriter().print(string);
			return null;
		} catch (IOException e) {
			return null;
		}
	}

	
	/**
	 * 授权登录异常
	 */
	@ExceptionHandler({AuthenticationException.class})
    public String authenticationException() {  
        return "error/403";
    }
	
	/**
	 * 初始化数据绑定
	 * 1. 将所有传递进来的String进行HTML编码，防止XSS攻击
	 * 2. 将字段中Date类型转换为String类型
	 */
	@InitBinder
	protected void initBinder(WebDataBinder binder) {/*
		// String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击
		binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
			}
			@Override
			public String getAsText() {
				Object value = getValue();
				return value != null ? value.toString() : "";
			}
		});
		// Date 类型转换
		binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				setValue(DateUtils.parseDate(text));
			}
//			@Override
//			public String getAsText() {
//				Object value = getValue();
//				return value != null ? DateUtils.formatDateTime((Date)value) : "";
//			}
		});
		SimpleDateFormat datetimeFormat = new SimpleDateFormat(
		 	                "yyyy-MM-dd HH:mm:ss");
		 	       datetimeFormat.setLenient(false);
		binder.registerCustomEditor(java.sql.Timestamp.class,
		 	                new CustomTimestampEditor(datetimeFormat, true));
	*/}
	
	public Page bindPageData(HttpServletRequest request){
		
		String sEcho = ""; 			//分页相关
		String iDisplayStart = "";	//开始显示行   
		String iDisplayLength = "";	//每页显示的长度 
		String sSearch="";			//全局收索  
		String iSortCol_0="";		//排序列
		String sortColName = "";	//排序列的名称
		String sSortDir_0="";		//排序
		int s = 0;//开始行
		int e = 0;//显示记录
		
		Map<String, String> colMap = new HashMap<>();
		String jsondata = request.getParameter("aoData");   
		JSONArray jsonarray = JSONArray.fromObject(jsondata);
		if(jsondata!=null){
			for (int i = 0; i<jsonarray.size(); i++) {       
				JSONObject obj = (JSONObject) jsonarray.get(i); 
			   if (obj.get("name").equals("sEcho"))     
				   sEcho = obj.get("value").toString();     
			   if (obj.get("name").equals("iDisplayStart"))     //开始显示行      
				   iDisplayStart = obj.get("value").toString();     
			   if (obj.get("name").equals("iDisplayLength"))     //每页显示的长度      
				   iDisplayLength = obj.get("value").toString(); 
			   if (obj.get("name").equals("sSearch"))     //全局收索      
				   sSearch = obj.get("value").toString(); 
			   if (obj.get("name").equals("iSortCol_0"))     //排序列     
				   iSortCol_0 = obj.get("value").toString(); 
			   if (obj.get("name").equals("sSortDir_0"))     //排序     
				   sSortDir_0 = obj.get("value").toString(); 
			   //列名存放到map中
			   if(obj.get("name").toString().startsWith("mDataProp_")){
				   colMap.put(obj.get("name").toString(),  obj.get("value").toString());
			   }
			}
			
			s = Integer.parseInt(iDisplayStart);
			e = Integer.parseInt(iDisplayStart)+Integer.parseInt(iDisplayLength);
		}
		
		Page page = Page.newBuilder(Integer.parseInt(iDisplayStart)+1,Integer.parseInt(iDisplayLength),null);  
		page.setPageNo(Integer.parseInt(iDisplayStart)/Integer.parseInt(iDisplayLength)+1);
		
		page.setSortDir(sSortDir_0);
		if (StringUtils.isNotBlank(iSortCol_0)) {
			int colIndex = Integer.parseInt(iSortCol_0);
			String colName = colMap.get("mDataProp_" + colIndex);
			if (StringUtils.isNotBlank(colName)) {
				page.setSortColName(colName);
			}
		}
		return page;
	}
	
	public String toPageJson(List<Map<String,Object>> result, Page page){
		String json =  "{\"iTotalRecords\":"+page.getTotalRecord()+",\"iTotalDisplayRecords\":"+page.getTotalRecord()+",\"aaData\":"+JSONArray.fromObject(result)+"}";  
		return json;
	}
	
	public Map<String,String> getPageInfo(String aoData){
		Map<String,String> map = new HashMap<String,String>();
		String iDisplayStart = "";	//开始显示行   
		String iDisplayLength = "";	//每页显示的长度 
		int page=0;
		String jsondata = aoData;   
		JSONArray jsonarray = JSONArray.fromObject(jsondata);
		if(jsondata!=null){
			for (int i = 0; i<jsonarray.size(); i++) {       
				JSONObject obj = (JSONObject) jsonarray.get(i); 
			   if (obj.get("name").equals("iDisplayStart"))     //开始显示行      
				   iDisplayStart = obj.get("value").toString();     
			   if (obj.get("name").equals("iDisplayLength"))     //每页显示的长度      
				   iDisplayLength = obj.get("value").toString(); 
			}
			
			page = Integer.parseInt(iDisplayStart)/Integer.parseInt(iDisplayLength)+1;
			
			//降序pagesize*(page-1)
			int num = Integer.parseInt(iDisplayLength) * (page - 1);
			map.put("page",String.valueOf(page));
			map.put("iDisplayLength", iDisplayLength);
			map.put("num", String.valueOf(num));
		}
		return map;
	}
	
    public String formatTableDisplay4Page(String aoData,List<Map<String, Object>> list,String totalRecords)  {
		
		String sEcho = ""; 			//分页相关
		String iDisplayStart = "";	//开始显示行   
		String iDisplayLength = "";	//每页显示的长度 
		String sSearch="";			//全局收索  
		String iSortCol_0="";		//排序列
		String sSortDir_0="";		//排序
		int s = 0;//开始行
		int e = 0;//显示记录
		String jsondata = aoData;   
		JSONArray jsonarray = JSONArray.fromObject(jsondata);
		if(jsondata!=null){
			for (int i = 0; i<jsonarray.size(); i++) {       
				JSONObject obj = (JSONObject) jsonarray.get(i); 
			   if (obj.get("name").equals("sEcho"))     
				   sEcho = obj.get("value").toString();     
			   if (obj.get("name").equals("iDisplayStart"))     //开始显示行      
				   iDisplayStart = obj.get("value").toString();     
			   if (obj.get("name").equals("iDisplayLength"))     //每页显示的长度      
				   iDisplayLength = obj.get("value").toString(); 
			   if (obj.get("name").equals("sSearch"))     //全局收索      
				   sSearch = obj.get("value").toString(); 
			   if (obj.get("name").equals("iSortCol_0"))     //排序列     
				   iSortCol_0 = obj.get("value").toString(); 
			   if (obj.get("name").equals("sSortDir_0"))     //排序     
				   sSortDir_0 = obj.get("value").toString(); 
			}
			
			s = Integer.parseInt(iDisplayStart);
			e = Integer.parseInt(iDisplayStart)+Integer.parseInt(iDisplayLength);
		}
		//如果收索字段不为空，则进行收索过滤
		if(StringUtils.isNotEmpty(sSearch)){
			list = getSearchforReportDown(list, sSearch);
		}
		String json = null; // 返回的json数据  
		//String aaData=JSONArray.fromObject(list.subList(s, e>list.size()?list.size():e)).toString();    
		String aaData=JSONArray.fromObject(list).toString();
		json =  "{\"sEcho\":"+sEcho+",\"iTotalRecords\":"+totalRecords+",\"iTotalDisplayRecords\":"+totalRecords+",\"aaData\":"+aaData+"}";  
		
		return json; 
	}

    //收索和排序方法，按照参数对数据进行收索和排序
	public List<Map<String, Object>> getSearchforReportDown(List<Map<String, Object>> list,String search){
		List<Map<String, Object>> listA = new ArrayList<Map<String, Object>>();
		for (Map<String, Object> map : list) {
				Set<String> set = map.keySet();
				for (String str : set) {
					Object value = map.get(str);
					if(StringUtils.isNotEmpty(str)&&value!=null&&value.toString().indexOf(search)!=-1){
						listA.add(map);
						break;
					}
				}
		}
		return listA;
	}
}